const puppeteer = require('puppeteer')

const url = 'https://movie.douban.com/top250'
const timeout = function () {
    return new Promise(resolve => setTimeout(resolve, 2000))
}
const theatersCrawler = async () => {
    const browser = await puppeteer.launch(
        {
            args: ['--no-sandbox'],
            // headless: false    //以无头浏览器的形式打开浏览器，没有界面显示，在后台运行的
        }
    );
    //2. 创建tab标签页
    const page = await browser.newPage();
    //3. 跳转到指定网址
    await page.goto(url, {
        waitUntil: 'networkidle2'  //等待网络空闲时，在跳转加载页面
    });
    //4. 等待网址加载完成，开始爬取数据
    //开启延时器，延时2秒钟
    await timeout();
    // 开始爬取数据
    let result = await page.evaluate(()=>{
        let data = []
        let doms = $('.grid_view > li > .item')
        for(let i = 0  ; i<8 ; i ++ ){
            let $dom = $(doms[i])
            //电影的详情页网址
            let href = $dom.find('.pic a').attr('href')
            let title = $dom.find('.info .title')[0].innerText
            let doubanId = href.split('/')
            //  //电影海报图
            let image = $dom.find('.pic img').attr('src');
            let rating = $dom.find('.rating_num').text()
            let director = $dom.find('.bd p')[0].innerText.replace(/\s+/g,'')
            data.push({
                title,
                doubanId:parseInt(doubanId[doubanId.length-2]) ,
                href,
                image,
                rating,
                director
            })
        }
        return data
    })
    console.log(result)
    //5. 关闭浏览器
    await browser.close();
    return result
}

module.exports = theatersCrawler